<?php

namespace app\user\controller;


use think\Controller;
use think\Exception;
use think\facade\Log;
use think\Request;
use app\common\model\RelationMap;
use app\common\lib\Util;
use app\common\lib\Netease as ease;

class RelationShip extends Controller
{
    /*导图展示*/
    public function map(Request $request)
    {
        $accid = $request->accid ? $request->accid : 0;
        if (!$accid) {
            throw new Exception('参数错误');
        }
        $this->assign('accid',$accid);
        return $this->fetch();
    }

    //生成导图
    public function createRelationMap(Request $request, ease $ease)
    {
        $accid = $request->param('accid') ? $request->param('accid') : 0;
        if (!$accid) {
            throw new Exception('参数错误');
        }
        $data = ['accid' => $accid, 'updatetime' => 1563847394];
        $result = $ease->friendList($data);
        if ($result == false) {
            return Util::apiResponse([], '参数错误', 400);
        }
        if ($result['error'] == 1) {
            return Util::apiResponse([], $result['message'], 400);
        }
        foreach ($result['list'] as $k => &$v) {
            $faccid = $v['faccid'];
            if (!isset($v['name'])) {
                $info = $ease->getUinfos([$faccid]);
                if ($info['error'] == 1) {
                    return Util::apiResponse([], $result['message'], 400);
                }
                $v['name'] = isset($info['name']) ? $info['name'] : '未设置昵称';
            } else {
                $v['name'] = $v['alias'];
            }
        }
        $relation = [
            'name' => '我'
        ];
        //设置数组键值对
        $arrKey = [];
        if (is_array($result['list']) && count($result['list']) > 0) {
            $relationList = $result['list'];
            foreach ($relationList as $k => $v2) {
                if (isset($v2['ex'])) {
                    $ex = json_decode($v2['ex'], true);
                    if (isset($ex['relation'])) {
                        if(in_array($ex['relation']['id'],$arrKey)){
                            $key = array_search($ex['relation']['id'],$arrKey);
                        }else{
                            $arrKey[$k] = $ex['relation']['id'];
                            $key = $k;
                        }
                        $relation['children'][$key]['name'] = $ex['relation']['name'];
                        $relation['children'][$key]['children'][]['name'] = isset($v2['alias']) ? $v2['alias'] : $v2['name'];
                    }
                }
            }
        }
        return Util::apiResponse($relation, '', 1);
    }
}
